package logic

import (
	"context"
	"log"
	"strconv"

	"github.com/gagliardetto/solana-go"
	"github.com/gagliardetto/solana-go/rpc"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gtime"
)

type SolanaLogic struct{}

const (
	// USDT 的 SPL 代币地址
	usdtTokenAddress = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"
)

var usdtPubkey = solana.MustPublicKeyFromBase58(usdtTokenAddress)
var rpcClient *rpc.Client
var rpcURL string

func (s *SolanaLogic) MatchTrade(wallet string, amount float64, createdAt *gtime.Time) bool {
	rpcURL = g.Cfg().MustGet(gctx.New(), "solana.url").String()
	rpcClient = rpc.New(rpcURL)
	walletPubkey := solana.MustPublicKeyFromBase58(wallet)
	limit := 10
	signatures, err := rpcClient.GetSignaturesForAddressWithOpts(
		context.Background(),
		walletPubkey,
		&rpc.GetSignaturesForAddressOpts{
			Limit: &limit,
		},
	)

	if err != nil {
		log.Printf("获取签名失败: %v", err)
		return false
	}
	for _, sig := range signatures {

		// 获取交易详情
		tx, err := rpcClient.GetTransaction(context.Background(), sig.Signature, nil)
		if err != nil {
			log.Printf("获取交易详情时出错: %v", err)
			continue
		}

		// 解析交易，检查是否为 USDT 交易
		if tx != nil && tx.Meta != nil {
			// 获取交易时间
			transactionTime := tx.BlockTime

			for _, balance := range tx.Meta.PostTokenBalances {

				if balance.Mint == usdtPubkey {
					owner := balance.Owner.String() // 代币持有者地址
					// 检查余额变化方向
					isIncoming := owner == wallet // 是否是转入交易
					if isIncoming {
						tradeAmount, err := strconv.ParseFloat(balance.UiTokenAmount.UiAmountString, 64)
						if err != nil {
							log.Printf("解析交易金额时出错: %v", err)
							return false
						}
						transactionTimeUnix := transactionTime.Time() // 将交易时间转换为 Unix 时间戳
						createdAtUnix := createdAt.Unix()             // 将创建时间转换为 Unix 时间戳
						if tradeAmount == amount && (transactionTimeUnix.Unix()-createdAtUnix) <= 30*60 {
							return true
						}

					}
				}
			}
		}
	}
	return false
}
